<template>
  <span @click.stop="handleCopy" style="cursor: pointer">
    <slot></slot>
    <span v-if="Object.keys($slots).length == 0 || Object.keys($slots).findLastIndex(e => e != 'suffix') != -1">{{ value }}</span>
    <Icon :icon="icon" v-if="!Object.keys($slots)['suffix']" :style="style" class="ml-1 copy-text" />
    <slot name="suffix"></slot>
  </span>
</template>

<script lang="ts" setup>
  import { unref, PropType, CSSProperties } from "vue"
  import { useRouter } from "vue-router"
  import Icon from "/@/components/Icon"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { useCopyToClipboard } from "/@/hooks/web/useCopyToClipboard"
  const router = useRouter()
  const props = defineProps({
    icon: { type: String, default: "ant-design:copy-outlined" },
    value: { type: [String, Number, Boolean, Object] },
    style: {
      type: Object as PropType<CSSProperties>,
      default: { fontSize: "14px" },
    },
  })

  const { createMessage } = useMessage()
  const { clipboardRef, copiedRef } = useCopyToClipboard()

  function handleCopy() {
    const value = unref(props.value)
    if (!value) {
      createMessage.warning("请输入要拷贝的内容！")
      return
    }
    clipboardRef.value = value
    if (unref(copiedRef)) {
      createMessage.success("复制成功")
    }
  }
  defineExpose({
    handleCopy,
  })
</script>

<style lang="less" scoped>
  .copy-text:hover {
    color: #1890ff;
    text-decoration: none;
    background-color: transparent;
    outline: none;
    cursor: pointer;
    transition: color 0.3s;
  }
</style>
